<?php

namespace app\model;

use think\helper\Str;
use think\Model;

class Supplier extends Model
{
    public function addOrUpdate(): array
    {
        $param = request()->post();
        if (empty($param['id'])) {
            $param['appid'] = $this->setAppId();
            $param['token'] = $this->setAppSecret();
        }
        $this->exists(!empty($param['id']))->save($param);
        return $this->toArray();
    }

    public function lst(): array
    {
        $param = request()->param();
        return pageData($this->order(['create_time' => 'desc'])->paginate([
            'list_rows' => $param['size'] ?? 30,
            'page' => $param['page'] ?? 1,
        ]));
    }

    protected function setAppId(): string
    {
        $code = Str::random(8, 1);
        $count = $this->where('appid', $code)->count();
        if ($count > 0) {
            return $this->setAppId();
        }
        return $code;
    }

    protected function setAppSecret(): string
    {
        return Str::random(32, 9);
    }
}
